package com.appology.chuck;


import com.google.api.client.extensions.appengine.auth.AbstractAppEngineFlowServlet;
import com.google.api.client.extensions.auth.helpers.Credential;
import com.google.api.client.extensions.auth.helpers.ThreeLeggedFlow;
import com.google.api.client.googleapis.extensions.auth.helpers.oauth2.draft10.GoogleOAuth2ThreeLeggedFlow;
import com.google.api.services.buzz.Buzz;
import com.google.api.services.buzz.Buzz.People;
import com.google.api.services.buzz.Buzz.People.Get;
import com.google.api.services.buzz.model.Activity;
import com.google.api.services.buzz.model.ActivityFeed;
import com.google.api.services.buzz.model.Person;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import java.io.IOException;
import java.io.PrintWriter;

import javax.jdo.PersistenceManagerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appology.jokes.Joke;
import com.appology.oauth2.*;

/**
 * This is the main entry point for the example. It uses the
 * {@link AbstractFlowUserServlet} to require an authorized session for the
 * current user prior to invoking the {@link
 * #doGetWithCredentials(HttpServletRequest, HttpServletResponse, Credential)}
 * method.
 *
 * @author moshenko@google.com (Jacob Moshenko)
 *
 */
public class SampleApp extends AbstractAppEngineFlowServlet {
  /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

@Override
  protected ThreeLeggedFlow newFlow(String userId) {
	
    return new GoogleOAuth2ThreeLeggedFlow(userId,
        OAuth2ClientCredentials.CLIENT_ID,
        OAuth2ClientCredentials.CLIENT_SECRET,
        OAuth2ClientCredentials.SCOPE,
        "http://appology-chuck-norris.appspot.com/oauth2callback");
  }

  @Override
  protected void doGetWithCredentials(
      HttpServletRequest req, HttpServletResponse resp, Credential credential) throws IOException {
	  UserService userService = UserServiceFactory.getUserService();
	  String thisURL = req.getRequestURI();
	  resp.setContentType("text/plain");
	  PrintWriter writer = resp.getWriter();
	  String id = null;
	  if (req.getUserPrincipal() != null) {          
		  id = userService.getCurrentUser().getUserId();
//          writer.println(userService.getCurrentUser().getUserId());   
      }
    // List activities using the generated client
    Buzz buzz = new Buzz(getHttpTransport(), credential, getJsonFactory());
    People people = buzz.people;
    Get get = people.get("@me");
    Person person = get.execute();
    
//    writer.println(id);
    String name = (String) person.displayName;
    
	
	ChuckUser chuckUser = new ChuckUser(id, person.id.toString(), name);
	chuckUser.save();
//    //Use an aId so that we can guarantee that the id will 
//    //fall into our random number generator
//    //ID - is auto-incremented therefore can be problematic
//	datastore.put(user);	
 
//    ActivityFeed activities = buzz.activities.list("me", "@self").execute();

//    writer.println(Joke.getInstance().getRandom(name));
    String destination  ="/index.jsp";        
    resp.sendRedirect(resp.encodeRedirectURL(destination));
//    writer.println("Stream for: " + name);
//    writer.println("Activities:");
//    for (Activity oneAct : activities.items) {
//      writer.println(oneAct.title);
//    }
  }

  @Override
  protected PersistenceManagerFactory getPersistenceManagerFactory() {
    return PMF.get();
  }
}